import { ref } from 'vue'

// 分页时，api接口的两个请求参数，为id,和page
export const commonIDPage = (opt = {}) => {
  const loading = ref(false)
  const hasMore = ref(false)
  const page = ref(1)
  const tableData = ref([])
  const activeId = ref(0)
  // 话题详情页的tabbar选项参数
  const tab = ref('hot')
  // 首次加载数据
  const isFirstLoad = ref(true)

  // 数据交互
  function loadData() {
    loading.value = true
    opt
      .getList(activeId?.value, page?.value, tab?.value)
      .then((res) => {
        if (
          opt.onGetListSuccess &&
          typeof opt.onGetListSuccess === 'function'
        ) {
          opt.onGetListSuccess(res)
        } else {
          tableData.value = res.data.data
        }
      })
      .finally(() => {
        isFirstLoad.value = false
        loading.value = false
      })
  }

  return {
    loading,
    hasMore,
    page,
    tableData,
    loadData,
    activeId,
    tab,
    isFirstLoad
  }
}

// api接口只有一个请求参数，为id
export const commonID = (opt = {}) => {
  const loading2 = ref(false)
  const tableData2 = ref(null)
  const activeId2 = ref(0)
  const isFirstLoad2 = ref(true)

  // 数据交互
  function loadData2() {
    loading2.value = true
    opt
      .getList(activeId2.value)
      .then((res) => {
        if (
          opt.onGetDetailSuccess &&
          typeof opt.onGetDetailSuccess === 'function'
        ) {
          opt.onGetDetailSuccess(res)
        } else {
          tableData2.value = res.data
        }
      })
      .finally(() => {
        isFirstLoad2.value = false
        loading2.value = false
      })
  }

  return {
    loading2,
    tableData2,
    activeId2,
    loadData2,
    isFirstLoad2
  }
}
